﻿#!/usr/bin/env python
#coding:utf-8

import os
import sys
import hashlib
import time
import re
import logging


# 初始化log
def init_log(filename=sys.argv[0]):
	LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
	DATE_FORMAT = "%Y%m%d %H:%M:%S"
	filename = filename + '.log'
	logging.basicConfig(filename=filename, level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)
	logging.info('\n\n')
	logging.info('========STARTUP pid=[%d] cmd=%s ========' % (os.getpid(), sys.argv))
	
	
# 取当前文件的绝对路径
def get_current_path() :
	all_my_file = sys.path[0] + '/' + __file__
	dir_name, file_name = os.path.split(all_my_file)
	return dir_name + '/'


# 在屏幕上打印buffer的内容
def dump_buffer(buf, len):
	line_size = 8;
	for i in range(len) :
		if ( i % line_size == 0):
			if (i !=0 ):	# 结尾，需要换号
				print;
			print "%04x  " % i,	# 开头，需要打印地址编号
		print "0x%02x" % struct.unpack_from("B", buf, i),
	print;
	return;

# 美化输出字典对象
def pretty_dict(obj, indent=' '):
	def _pretty(obj, indent):
		for i, tup in enumerate(obj.items()):
			k, v = tup

			# 如果是字符串则拼上""
			if isinstance(k, basestring): k = '"%s"' % k
			if isinstance(v, basestring): v = '"%s"' % v

			# 如果是字典则递归

			if isinstance(v, dict):
				v = ''.join(_pretty(v, indent + ' ' * len(str(k) + ': {')))  # 计算下一层的indent

			# case,根据(k,v)对在哪个位置确定拼接什么
			if i == 0:  # 开头,拼左花括号
				if len(obj) == 1:
					yield '{%s: %s}' % (k, v)
				else:
					yield '{%s: %s,\n' % (k, v)
			elif i == len(obj) - 1:  # 结尾,拼右花括号
				yield '%s%s: %s}' % (indent, k, v)
			else:  # 中间
				yield '%s%s: %s,\n' % (indent, k, v)

	print ''.join(_pretty(obj, indent))


def get_twice_md5(ori_str) :
	m1 = hashlib.md5()
	m1.update(ori_str)
	m2 = hashlib.md5()
	m2.update(m1.hexdigest())
	return m2.hexdigest()


# 将列表转换成字符串 [1, 2, 3] -》'(1,2,3)'。   // 带有括号
#	改函数主要用于sql语句的in部分
#	防止出现(1,)这种形式，所以在len=1的时候需要单独处理
def fun_list_to_str(lst) :
	if 1 == len(lst):
		return '(%d)' % lst[0]
	else:
		return str(tuple(lst))

# 将,分割的字符串转换会list  '1,2,3' -> [1, 2, 3]   // 不带有括号，和上边的函数不是反函数
#	eg: fun_str_to_list('1,2,,3')
def fun_str_to_list(user_str, split_str=" |;|,|\||\t"):
	# 全角，变成半角的,
	user_str = user_str.replace('，', ',')

	# 根据分隔符进行拆分，目的是去除重复的分割符和空格等
	return [int(x) for x in re.split(" |;|,|\||\t", user_str) if x ]



# 简化SQL数据库查询语句
#	返回字典数据，可用于查询N行两列的数据内容（统计值，GroupBY），要求第一列内容不重复
'''
def sql_get_item_count(cursor, sql):
	
	value_dict = {}
	try:
		cursor = db.cursor()
		data = cursor.execute(sql)
		data = data.fetchall()
		for row in data:
			value_dict[ row[0] ] = row[1]

	except pymysql.Error,e:
		print '%s ' % str(e)
		cursor.close()		

	# 所有情况都在这里返回了
	finally:
		return value_dict
'''

def get_time_diff(start, end):
	sz = ''
	diff = end - start
	if (diff < 10 * 1000): #	// < 10s,, 1234ms
		sz = "%dms" % diff
	elif (diff < 3 * 60 * 1000):	#	// < 3min,, 1234.56sec
		sz = "%.2fsec" % ( diff / 1000)
	elif (diff < 1 * 3600 * 1000):	#// < 1hour,, 13:56min, 13分56秒
		sec = diff / 1000;
		sz = "%d:%dmin" %( sec / 60, sec % 60)
	else:	#// 1:34hour， 1小时34分
		min = diff / (60 * 1000);
		sz = "%d:%dhour" % ( min / 60, min % 60)

	return sz;



# 取毫秒的时间戳（unix时间戳）
current_milli_time = lambda: int(round(time.time() * 1000))

class ProgressBar:
	def	__init__(self, posi = 0, total	= 0, max = 100, showtime = 0):
		self.posi = posi
		self.total = total
		self.MAX = max
		self.out = ''
		self.SHOWTIME = showtime
		self.time_begin = time.time() * 1000


	# 显示百分比进度条（posi是逐渐变大的，所以不需要清除上一次的显示部分）
	def do_process(self, posi):
		self.posi = posi
		self.out = ' (%d/%d)(%.2f%%)' % (self.posi, self.total, float(self.posi)*100/self.total) 

		if self.SHOWTIME != 0:
			time_end = time.time() * 1000
			self.out += '(%s)' % ( get_time_diff(self.time_begin, time_end) )

		passed = self.MAX * self.posi / self.total
		sys.stdout.write('\r' + '█'*passed + '░'*(self.MAX-passed) + self.out + '\r')
		if passed >= self.MAX:
			sys.stdout.write('\n')
		sys.stdout.flush()

	# 输出正常的信息
	def	log(self, s):
		sys.stdout.write('\r' + ' ' * (self.MAX+len(self.out)) + '\r')
		print s
		self.do_process(self.posi)



#▁▂▃▄▅▆▇█▉▊▋▌▍▓ ░ ▒▒ ▒░ ▒
if __name__ == '__main__':
	import time
	bar	= ProgressBar(total=100, max=30)
	for	i in range(101):
		if 0==i%10:
			bar.log('We have arrived at: ' + str(i + 1))
		bar.do_process(i)
		time.sleep(0.1)